package com.cls.business.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.cls.business.entity.*;
import com.cls.business.service.IIndicatorService;
import com.cls.business.service.IReviewService;
import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.utils.MyUtil;
import com.cls.common.entity.MyConstant;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.QueryRequest;
import com.cls.common.entity.ResponseVO;
import com.cls.system.entity.User;
import com.github.pagehelper.PageInfo;
import com.cls.business.service.IStandardService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 评审标准表 Controller
 *
 * @author wmm
 * @date 2020-11-11 16:25:41
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class StandardController extends BaseController {

    private final IStandardService standardService;
    private final IIndicatorService indicatorService;
    private final IReviewService reviewService;
    /**
    * 评审标准表列表页面
    **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard")
    public String standardIndex(){
        return MyUtil.view("business/standard/standard");
    }

    /**
    * 评审标准表新增页面
    * @return
    */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/standardAdd")
    public String standardAdd(Model model){
        return MyUtil.view("business/standard/standardAdd");
    }

    /**
     * 评审标准表新增页面
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/detail/add")
    public String standardDetailAdd(Model model){
        return MyUtil.view("business/standard/standardDetailAdd");
    }

    /**
     * 评审标准表编辑页面
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/detail/update")
    public String standardDetailUpdate(Model model){
        return MyUtil.view("business/standard/standardDetailUpdate");
    }


    /**
     * 评审标准表新增页面
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/indictor/add/{standardId}")
    public String standardIndictorAdd(@PathVariable Long standardId,Model model)
    {
        model.addAttribute("standardId",standardId);
        return MyUtil.view("business/standard/indicator/indicatorAdd");
    }

    /**
    * 评审标准表修改页面
    * @return
    */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/standardUpdate/{standardId}")
    public String standardUpdate(@PathVariable Long standardId, Model model){
        Standard standard = standardService.getById(standardId);
        model.addAttribute("standard",standard);
        return MyUtil.view("business/standard/standardUpdate");
    }


    /**
    * 评审标准详情页面
    * @return
    */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/standard/detail/{standardId}")
    public String standardDetail(@PathVariable Long standardId, Model model){
        Standard standard = standardService.getById(standardId);
        Indicator indicator =new Indicator();
        indicator.setIndicatorId(standardId);
        List<Indicator> indicators = indicatorService.findIndicators(indicator);
        standard.setIndicatorLists(indicators);
        model.addAttribute("standard",standard);
        return MyUtil.view("business/standard/standardDetail");
    }
    @GetMapping("standard/getList")
    @ResponseBody
    public ResponseVO getListStandards() {
        return ResponseVO.success(standardService.getListStandards());
    }


    @GetMapping("standard")
    @ResponseBody
    @RequiresPermissions("standard:list")
    public ResponseVO getAllStandards(Standard standard) {
        return ResponseVO.success(standardService.findStandards(standard));
    }

    @GetMapping("standard/list")
    @ResponseBody
    @RequiresPermissions("standard:list")
    public ResponseVO standardList(QueryRequest request, Standard standard) {
        standard.setSnapshot(false);
        PageInfo<Standard> pageInfo =  this.standardService.findStandards(request, standard);
        return ResponseVO.success(pageInfo);
    }

    @ControllerEndpoint(operation = "新增", exceptionMessage = "新增失败")
    @PostMapping("standard")
    @ResponseBody
    @RequiresPermissions("standard:add")
    public ResponseVO addStandard(String json) {
        StandardJson standardJson = JSONUtil.toBean(json, StandardJson.class);
        //判断数据格式
        List<StandardDateilDate> listSoure = standardJson.getListSoure();
        Double allWeight=0.0;
        for (StandardDateilDate data:listSoure) {
            Double weight= Double.valueOf(data.getWeight());
            allWeight+=weight;

            //验证分值
            String[] indicatorTypeStrArr=data.getIndicatorTypeStrArr();
            String[] maxScoreStrArr=data.getMaxScoreStrArr();
            String[] minScoreStrArr=data.getMinScoreStrArr();
            List<IndicatorDetail> listAll=new ArrayList<>();
            for (int i=0;i<indicatorTypeStrArr.length; i++) {
                IndicatorDetail indicatorDetail=new IndicatorDetail();
                indicatorDetail.setIndicatorType(indicatorTypeStrArr[i]);
                indicatorDetail.setMaxScore(Double.valueOf(maxScoreStrArr[i]));
                indicatorDetail.setMinScore(Double.valueOf(minScoreStrArr[i]));
                listAll.add(indicatorDetail);
            }
            //比较大小
            for (IndicatorDetail score:listAll) {
                if(score.getMinScore()>score.getMaxScore()){
                    return ResponseVO.failure("新增失败！课题名称："+data.getName()+"的 "+score.getIndicatorType()+"最大值要大于最小值分数！");
                }
            }
            //排序
            int sizNum=  listAll.size();
            int sizNumLast=  sizNum-1;
            if(sizNum>1){
                listAll.sort(Comparator.comparing(IndicatorDetail::getIndicatorType));
                for (int i=0; i <sizNum;i++){
                 // 比较大小
                    IndicatorDetail item=listAll.get(i);

                    if(i==0){
                        //比较第一个时候
                        IndicatorDetail lowerDate = listAll.get(i+1);
                        if((lowerDate.getMaxScore()>=item.getMinScore())) {
                            //报错
                            return ResponseVO.failure("新增失败！课题名称："+data.getName()+"的"+item.getIndicatorType()+"最小值要大于"+lowerDate.getIndicatorType()+"的最大值！");
                        }
                    }else if(i==sizNumLast){
                        //最后一名
                        IndicatorDetail upperDate = listAll.get(i-1);
                        if((item.getMaxScore()>=upperDate.getMinScore())) {
                            //报错
                            return ResponseVO.failure("新增失败！"+data.getName()+"的"+item.getIndicatorType()+"最大值要小于"+upperDate.getIndicatorType()+"最小值！");
                        }
                    }else {
                        //在二者之间
                        IndicatorDetail upperDate = listAll.get(i-1);
                        IndicatorDetail lowerDate = listAll.get(i+1);
                        if((item.getMaxScore()>=upperDate.getMinScore())) {
                            //报错
                            return ResponseVO.failure("新增失败！"+data.getName()+"的"+item.getIndicatorType()+"最大值要小于"+upperDate.getIndicatorType()+"的最小值！");
                        }
                        if((lowerDate.getMaxScore()>=item.getMinScore())) {
                            //报错
                            return ResponseVO.failure("新增失败！"+data.getName()+"的"+item.getIndicatorType()+"最小值要大于"+lowerDate.getIndicatorType()+"最大值！");
                        }
                    }
                }
            }
        }
        if(allWeight>100){
          return ResponseVO.failure("新增失败！权重之和超过100");
        }

        this.standardService.createStandardAll(standardJson);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "多个删除Standard", exceptionMessage = "删除失败")
    @PostMapping("standard/deletes/{ids}")
    @ResponseBody
    @RequiresPermissions("standard:delete")
    public ResponseVO deleteStandards(@PathVariable String ids) {
        String[] idArry = ids.split(StringPool.COMMA);
        this.standardService.deleteStandards(idArry);
        return ResponseVO.success();
    }


    @ControllerEndpoint(operation = "删除单个Standard", exceptionMessage = "删除失败")
    @PostMapping("standard/delete/{standardId}")
    @ResponseBody
    @RequiresPermissions("standard:delete")
    public ResponseVO deleteStandard(@PathVariable Long standardId) {
      // this.standardService.removeById(standardId);
      //循环删除
        this.standardService.removeAllById(standardId);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "修改Standard", exceptionMessage = "修改失败")
    @PostMapping("standard/update")
    @ResponseBody
    @RequiresPermissions("standard:update")
    public ResponseVO updateStandard(Standard standard) {
        this.standardService.updateStandard(standard);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "修改Standard", exceptionMessage = "导出Excel失败")
    @PostMapping("standard/excel")
    @ResponseBody
    @RequiresPermissions("standard:export")
    public void export(QueryRequest queryRequest, Standard standard, HttpServletResponse response) {
        List<Standard> standards = this.standardService.findStandards(queryRequest, standard).getList();
        ExcelKit.$Export(Standard.class, response).downXlsx(standards, false);
    }
}
